package com.ccrfid.rmc6.lbservice3.manager;

import com.ccrfid.rmc6.entity.alarm.AlarmRecordEntity;
import com.ccrfid.rmc6.entity.personnel.PersonnelEntity;
import com.ccrfid.rmc6.entity.poi.PoiLocationEntity;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmCall;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmCutoffStatus;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmLowpowerStatus;
import com.ccrfid.rmc6.lbservice3.pojo.alarm.AlarmOnlineStatus;
import com.ccrfid.rmc6.lbservice3.pojo.evt.EvtCardOffline;
import com.ccrfid.rmc6.pojo.Constants;
import com.ccrfid.rmc6.service.alarm.AlarmNotifyService;
import com.ccrfid.rmc6.service.alarm.AlarmRecordService;
import com.ccrfid.rmc6.service.personnel.PersonnelService;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.Timestamp;

@Component
public class CardAlarmManager {
    private static final Logger logger = LoggerFactory.getLogger(CardAlarmManager.class);
    @Autowired
    private EventBus eventBus;
    @Autowired
    private AlarmRecordService alarmRecordService;
    @Autowired
    private PersonnelService personnelService;
    @Autowired
    private AlarmNotifyService alarmNotifyService;

    @Value("${card.alarm.call.open}")
    private Boolean alarmCallOpen;
    @Value("${card.alarm.cutoff.open}")
    private Boolean alarmCutoffOpen;
    @Value("${card.alarm.lowpower.open}")
    private Boolean alarmLowpowerOpen;
    @Value("${card.alarm.offline.open}")
    private Boolean alarmOfflineOpen;

    @Value("${card.alarm.call.linkage.mode}")
    private String alarmCallLinkageMode;
    @Value("${card.alarm.cutoff.linkage.mode}")
    private String alarmCutoffLinkageMode;
    @Value("${card.alarm.lowpower.linkage.mode}")
    private String alarmLowpowerLinkageMode;
    @Value("${card.alarm.offline.linkage.mode}")
    private String alarmOfflineLinkageMode;

    @PostConstruct
    private void init() {
        this.eventBus.register(this);
        logger.info("card alarm switch status: call-{}, cutoff-{}, lowpower-{}, offline-{}",
                alarmCallOpen, alarmCutoffOpen, alarmLowpowerOpen, alarmOfflineOpen);
    }

    @Subscribe
    public void onAlarmCall(AlarmCall alarmCall) {
        if (!alarmCallOpen) {
            return;
        }
        PersonnelEntity personnelEntity = personnelService.getPersonnelByCardNumber(alarmCall.getCardNumber());
        if (personnelEntity != null && personnelEntity.getEnabled().equals(Constants.ENABLE_STATUS.ENABLE.id)) {
            AlarmRecordEntity recordEntity = alarmRecordService.getAlarmCallRecordInMinute(alarmCall.getCardNumber(), alarmCall.getTime());
            if (recordEntity != null) {
                //忽略处理1分钟内的重复呼叫告警
                logger.debug("ignore AlarmCall: {}", alarmCall);
            } else {
                //创建新告警记录
                recordEntity = new AlarmRecordEntity();
                recordEntity.setPersonnelId(personnelEntity.getId());
                recordEntity.setPersonnelName(personnelEntity.getPersonnelName());
                recordEntity.setNameAcronym(personnelEntity.getNameAcronym());
                recordEntity.setCardNumber(alarmCall.getCardNumber());
                PoiLocationEntity locationEntity = personnelService.getPersonnel3LevelLocation(personnelEntity.getId());
                if (locationEntity != null) {
                    recordEntity.setLocationId(locationEntity.getId());
                    recordEntity.setLocationName(locationEntity.getLocationName());
                }
                recordEntity.setAlarmRuleId(0L);
                recordEntity.setAlarmRuleName(Constants.ALARM_TYPE.CALL.name);
                recordEntity.setAlarmType(Constants.ALARM_TYPE.CALL.id);
                recordEntity.setAlarmTypeName(Constants.ALARM_TYPE.CALL.name);
                recordEntity.setAlarmLevel(Constants.ALARM_LEVEL.MINOR.id);
                recordEntity.setAlarmTime(new Timestamp(alarmCall.getTime()));
                recordEntity.setAlarmLinkageMode(alarmCallLinkageMode);
                recordEntity = alarmRecordService.createAlarmRecord(recordEntity);
                //推送告警
                alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                logger.info("notify AlarmCall, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
            }
        }
    }

    private void closeAlarmRecord(AlarmRecordEntity recordEntity, Long closeTime) {
        recordEntity.setClosed(1);
        recordEntity.setCloseTime(new Timestamp(closeTime));
        alarmRecordService.updateAlarmRecord(recordEntity);
    }

    @Subscribe
    public void onAlarmCutoffStatus(AlarmCutoffStatus alarmCutoffStatus) {
        PersonnelEntity personnelEntity = personnelService.getPersonnelByCardNumber(alarmCutoffStatus.getCardNumber());
        if (personnelEntity != null && personnelEntity.getEnabled().equals(Constants.ENABLE_STATUS.ENABLE.id)) {
            if (alarmCutoffStatus.getCutoffStatus().equals(Constants.CUTOFF_STATUS.CUTOFF.id)) {
                if (!alarmCutoffOpen) {
                    return;
                }
                //剪断告警
                AlarmRecordEntity recordEntity = alarmRecordService.getAlarmCutoffRecordUnClosed(alarmCutoffStatus.getCardNumber());
                if (recordEntity != null) {
                    //该标签存在未关闭的剪断告警，忽略处理
                    logger.debug("ignore AlarmCutoffStatus: {}", alarmCutoffStatus);
                } else {
                    //创建新告警记录
                    recordEntity = new AlarmRecordEntity();
                    recordEntity.setPersonnelId(personnelEntity.getId());
                    recordEntity.setPersonnelName(personnelEntity.getPersonnelName());
                    recordEntity.setNameAcronym(personnelEntity.getNameAcronym());
                    recordEntity.setCardNumber(alarmCutoffStatus.getCardNumber());
                    PoiLocationEntity locationEntity = personnelService.getPersonnel3LevelLocation(personnelEntity.getId());
                    if (locationEntity != null) {
                        recordEntity.setLocationId(locationEntity.getId());
                        recordEntity.setLocationName(locationEntity.getLocationName());
                    }
                    recordEntity.setAlarmRuleId(0L);
                    recordEntity.setAlarmRuleName(Constants.ALARM_TYPE.CUTOFF.name);
                    recordEntity.setAlarmType(Constants.ALARM_TYPE.CUTOFF.id);
                    recordEntity.setAlarmTypeName(Constants.ALARM_TYPE.CUTOFF.name);
                    recordEntity.setAlarmLevel(Constants.ALARM_LEVEL.MINOR.id);
                    recordEntity.setAlarmTime(new Timestamp(alarmCutoffStatus.getTime()));
                    recordEntity.setClosed(0);
                    recordEntity.setAlarmLinkageMode(alarmCutoffLinkageMode);
                    recordEntity = alarmRecordService.createAlarmRecord(recordEntity);
                    //推送告警
                    alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                    logger.info("notify AlarmCutoffStatus, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
                }
            } else if (alarmCutoffStatus.getCutoffStatus().equals(Constants.CUTOFF_STATUS.NORMAL.id)) {
                //剪断恢复
                AlarmRecordEntity recordEntity = alarmRecordService.getAlarmCutoffRecordUnClosed(alarmCutoffStatus.getCardNumber());
                if (recordEntity != null) {
                    closeAlarmRecord(recordEntity, alarmCutoffStatus.getTime());
                    //推送恢复信息
                    alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                    logger.info("notify AlarmCutoffStatus, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
                }
            }
        }
    }

    @Subscribe
    public void onAlarmLowpowerStatus(AlarmLowpowerStatus alarmLowpowerStatus) {
        PersonnelEntity personnelEntity = personnelService.getPersonnelByCardNumber(alarmLowpowerStatus.getCardNumber());
        if (personnelEntity != null && personnelEntity.getEnabled().equals(Constants.ENABLE_STATUS.ENABLE.id)) {
            if (alarmLowpowerStatus.getLowpowerStatus().equals(Constants.LOWPOWER_STATUS.LOWPOWER.id)) {
                if (!alarmLowpowerOpen) {
                    return;
                }
                //低电告警
                AlarmRecordEntity recordEntity = alarmRecordService.getAlarmLowpowerRecordUnClosed(alarmLowpowerStatus.getCardNumber());
                if (recordEntity != null) {
                    //该标签存在未关闭的低电告警，忽略处理
                    logger.debug("ignore AlarmLowpowerStatus: {}", alarmLowpowerStatus);
                } else {
                    //创建新告警记录
                    recordEntity = new AlarmRecordEntity();
                    recordEntity.setPersonnelId(personnelEntity.getId());
                    recordEntity.setPersonnelName(personnelEntity.getPersonnelName());
                    recordEntity.setNameAcronym(personnelEntity.getNameAcronym());
                    recordEntity.setCardNumber(alarmLowpowerStatus.getCardNumber());
                    PoiLocationEntity locationEntity = personnelService.getPersonnel3LevelLocation(personnelEntity.getId());
                    if (locationEntity != null) {
                        recordEntity.setLocationId(locationEntity.getId());
                        recordEntity.setLocationName(locationEntity.getLocationName());
                    }
                    recordEntity.setAlarmRuleId(0L);
                    recordEntity.setAlarmRuleName(Constants.ALARM_TYPE.LOWPOWER.name);
                    recordEntity.setAlarmType(Constants.ALARM_TYPE.LOWPOWER.id);
                    recordEntity.setAlarmTypeName(Constants.ALARM_TYPE.LOWPOWER.name);
                    recordEntity.setAlarmLevel(Constants.ALARM_LEVEL.MINOR.id);
                    recordEntity.setAlarmTime(new Timestamp(alarmLowpowerStatus.getTime()));
                    recordEntity.setClosed(0);
                    recordEntity.setAlarmLinkageMode(alarmLowpowerLinkageMode);
                    recordEntity = alarmRecordService.createAlarmRecord(recordEntity);
                    //推送告警
                    alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                    logger.info("notify AlarmLowpowerStatus, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
                }
            } else if (alarmLowpowerStatus.getLowpowerStatus().equals(Constants.LOWPOWER_STATUS.NORMAL.id)) {
                //低电恢复
                AlarmRecordEntity recordEntity = alarmRecordService.getAlarmLowpowerRecordUnClosed(alarmLowpowerStatus.getCardNumber());
                if (recordEntity != null) {
                    closeAlarmRecord(recordEntity, alarmLowpowerStatus.getTime());
                    //推送恢复信息
                    alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                    logger.info("notify AlarmLowpowerStatus, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
                }
            }
        }
    }

    @Subscribe
    public void onAlarmOnlineStatus(AlarmOnlineStatus alarmOnlineStatus) {
        PersonnelEntity personnelEntity = personnelService.getPersonnelByCardNumber(alarmOnlineStatus.getCardNumber());
        if (personnelEntity != null && personnelEntity.getEnabled().equals(Constants.ENABLE_STATUS.ENABLE.id)) {
            if (alarmOnlineStatus.getOnlineStatus().equals(Constants.ONLINE_STATUS.OFFLINE.id)) {
                if (alarmOfflineOpen) {
                    //离线
                    AlarmRecordEntity recordEntity = alarmRecordService.getAlarmOfflineRecordUnClosed(alarmOnlineStatus.getCardNumber());
                    if (recordEntity != null) {
                        //该标签存在未关闭的离线告警，忽略处理
                        logger.debug("ignore AlarmOnlineStatus: {}", alarmOnlineStatus);
                    } else {
                        //创建新告警记录
                        recordEntity = new AlarmRecordEntity();
                        recordEntity.setPersonnelId(personnelEntity.getId());
                        recordEntity.setPersonnelName(personnelEntity.getPersonnelName());
                        recordEntity.setNameAcronym(personnelEntity.getNameAcronym());
                        recordEntity.setCardNumber(alarmOnlineStatus.getCardNumber());
                        PoiLocationEntity locationEntity = personnelService.getPersonnel3LevelLocation(personnelEntity.getId());
                        if (locationEntity != null) {
                            recordEntity.setLocationId(locationEntity.getId());
                            recordEntity.setLocationName(locationEntity.getLocationName());
                        }
                        recordEntity.setAlarmRuleId(0L);
                        recordEntity.setAlarmRuleName(Constants.ALARM_TYPE.OFFLINE.name);
                        recordEntity.setAlarmType(Constants.ALARM_TYPE.OFFLINE.id);
                        recordEntity.setAlarmTypeName(Constants.ALARM_TYPE.OFFLINE.name);
                        recordEntity.setAlarmLevel(Constants.ALARM_LEVEL.MINOR.id);
                        recordEntity.setAlarmTime(new Timestamp(alarmOnlineStatus.getTime()));
                        recordEntity.setClosed(0);
                        recordEntity.setAlarmLinkageMode(alarmOfflineLinkageMode);
                        recordEntity = alarmRecordService.createAlarmRecord(recordEntity);
                        //推送告警
                        alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                        logger.info("notify AlarmOnlineStatus, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
                    }
                    //推送消息，清除标签位置
                    EvtCardOffline evtCardOffline = new EvtCardOffline(alarmOnlineStatus.getCardNumber(), personnelEntity.getId(), alarmOnlineStatus.getTime());
                    eventBus.post(evtCardOffline);
                }
            } else if (alarmOnlineStatus.getOnlineStatus().equals(Constants.ONLINE_STATUS.ONLINE.id)) {
                //上线
                AlarmRecordEntity recordEntity = alarmRecordService.getAlarmOfflineRecordUnClosed(alarmOnlineStatus.getCardNumber());
                if (recordEntity != null) {
                    closeAlarmRecord(recordEntity, alarmOnlineStatus.getTime());
                    //推送恢复信息
                    alarmNotifyService.postAlarmNotify(personnelEntity.getId(), recordEntity);
                    logger.info("notify AlarmOnlineStatus, personnelId: {}, alarmRecord: {}", personnelEntity.getId(), recordEntity);
                }
            }
        }
    }
}
